﻿/// <reference path="../typings/knockout/knockout.d.ts" />
/// <reference path="../typings/jquery/jquery.d.ts" />
/// <reference path="../typings/yandex.d.ts" />

module PhotoBlog
{
    export class OnePhotoVm
    {
        public Photo: KnockoutObservable<PhotoVm> = ko.observable(null);
        public load: (numberDay: number) => void;
        public afterRender: () => void;
        public enabledEdit: KnockoutObservable<boolean> = ko.observable(false);
        public enableEdit: () => void;
        public save: () => void;
        public prevImage: () => void;
        public nextImage: () => void;
        public paging: PhotoBlog.Models.PagingM = new PhotoBlog.Models.PagingM();
        public loaded: boolean = false;

        constructor(target: HTMLElement, public numberDay: number)
        {
            var urlBase = "http://mshots.ru/";
            var urlSite = urlBase + "day/";

            this.enableEdit = () =>
            {
                this.enabledEdit(!this.enabledEdit());
            };

            this.save = () =>
            {
                var photo = this.Photo().photo;
                PhotoBlog.Api.AsyncClient.Current.SavePhotos(photo, (result) =>
                {
                    if (!result) {
                        alert("Не сохранено");
                    }
                    this.enabledEdit(false);
                });
            };

            $(window).keydown(event =>
            {
                if (event.which == 39) {
                    this.nextImage();
                };
                if (event.which == 37) {
                    this.prevImage();
                };
            });

            this.prevImage = () =>
            {
                if (this.loaded) {
                    location.href = urlSite + this.paging.PrevPage;
                    this.loaded = false;
                }
            };

            this.nextImage = () =>
            {
                if (this.loaded) {
                    location.href = urlSite + this.paging.NextPage;
                    this.loaded = false;
                }
            };

            this.load = (day) =>
            {
                this.loaded = false;
                var getPhotosParams = new PhotoBlog.Models.GetPhotosParams();
                getPhotosParams.AlbumId = 1;
                getPhotosParams.NumberDay = day == undefined ? 1 : day;

                PhotoBlog.Api.AsyncClient.Current.GetDayPhoto(getPhotosParams, (result) =>
                {
                    if (result.PhotoM != null) {
                        this.Photo(new PhotoVm(result.PhotoM, () => { }, this.prevImage, this.nextImage));
                        var imageUrl = urlBase + result.PhotoM.Path;
                        $("#image_content").attr('content', imageUrl);
                        $("#image_src").attr('href', imageUrl);
                        this.Photo().description(result.PhotoM.Description);
                        this.Photo().music(result.PhotoM.Music);
                        this.paging = result.PagingM;
                        this.loaded = true;
                    } else {
                        location.href = '/error?errors=Фотография дня ' + day + ' не найдена';
                    }
                });
            };
            this.load(this.numberDay);

            this.afterRender = () =>
            {
                var url = urlBase + this.Photo().url;
                var href = location.href;
                new Ya.share({
                    element: 'yashare',
                    theme: 'counter',
                    elementStyle: {
                        'quickServices': ['vkontakte', 'facebook', 'twitter', 'odnoklassniki', 'gplus']
                    },
                    link: href,
                    image: url,
                    popupStyle: {
                        copyPasteField: true
                    }
                });
            };

            ko.applyBindings(this, target);
        }
    }

    export class FullscreenVm
    {
        public isFullScreen: KnockoutObservable<boolean> = ko.observable(false);
        public fullScreenOn: () => void;
        public fullScreenOff: () => void;
        public nextImage: () => void;
        public prevImage: () => void;

        constructor()
        {

            this.fullScreenOn = () =>
            {
                this.isFullScreen(true);
            };

            this.fullScreenOff = () =>
            {
                this.isFullScreen(false);
            };

            this.nextImage = () =>
            {

            };

            this.prevImage = () =>
            {

            };
        }
    }

    export class AlbumPhotosVm
    {
        public Albums: KnockoutObservableArray<AlbumVm> = ko.observableArray<AlbumVm>([]);
        public Album: KnockoutObservable<AlbumVm> = ko.observable(null);
        public Photos: KnockoutObservableArray<PhotoVm> = ko.observableArray<PhotoVm>([]);
        public load: (albumId: number) => void;
        public fullImage: KnockoutObservable<PhotoVm> = ko.observable(null);
        public isGridMode: KnockoutObservable<boolean> = ko.observable(true);
        public goFullScreen: (data: PhotoVm) => void;
        public backToAlbums: () => void;
        public isHovered: KnockoutObservable<boolean> = ko.observable(true);
        public isHover: (enable: boolean) => void;
        public prev: () => void;
        public next: () => void;
        public resetActivePhotos: () => void;

        constructor(target: HTMLElement, public id: number)
        {
            this.resetActivePhotos = () =>
            {
                var photos = this.Photos();
                for (var i = 0; i < photos.length; i++) {
                    photos[i].isActive(false);
                }
            };

            this.isHover = (enable) =>
            {
                this.isHovered(enable);
            };

            this.backToAlbums = () =>
            {
                this.isGridMode(true);
            };

            this.prev = () =>
            {
                var currentImage = this.fullImage();
                var photos = this.Photos();
                var photoIndex = photos.indexOf(currentImage);
                if (photoIndex !== -1) {
                    var index = photoIndex - 1;
                    if (index > -1) {
                        var photo = photos[index];
                        this.resetActivePhotos();
                        photo.isActive(true);
                        this.fullImage(photo);
                    }
                }
            };

            this.next = () =>
            {
                var currentImage = this.fullImage();
                var photos = this.Photos();
                var photoIndex = photos.indexOf(currentImage);
                if (photoIndex !== -1) {
                    var index = photoIndex + 1;
                    if (index <= photos.length - 1) {
                        var photo = photos[index];
                        this.resetActivePhotos();
                        photo.isActive(true);
                        this.fullImage(photo);
                    }
                }
            };

            this.goFullScreen = (photo) =>
            {
                this.resetActivePhotos();
                photo.isActive(true);
                this.fullImage(photo);
                this.isGridMode(false);
            };

            this.load = (albumId) =>
            {
                PhotoBlog.Api.AsyncClient.Current.GetAlbumPhotos(albumId, (result) =>
                {
                    var p = result.Photos.map((v) => { return new PhotoVm(v, this.goFullScreen, () => { }, () => { }); });
                    var a = result.Albums.map((v) => { return new AlbumVm(v); });
                    this.Album(new AlbumVm(result.Album));
                    this.Photos(p);
                    this.Albums(a);
                });
            };
            this.load(this.id);

            ko.applyBindings(this, target);
        }

    }

    export class AlbumVm
    {
        public showInfo: () => void;
        public hideInfo: () => void;
        public displayInfo: KnockoutObservable<boolean> = ko.observable(false);
        public url: string = "";
        public openAlbum: () => void;

        constructor(public album: PhotoBlog.Models.AlbumM)
        {
            this.url = '/' + album.Logo;

            this.showInfo = () =>
            {
                this.displayInfo(true);
            };

            this.hideInfo = () =>
            {
                this.displayInfo(false);
            };

            this.openAlbum = () =>
            {
                window.location.href = '/album/' + album.AlbumId + '/photos';
            };
        }
    }

    export class AlbumPageVm
    {
        public Albums: KnockoutObservableArray<AlbumVm> = ko.observableArray<AlbumVm>([]);
        public load: () => void;

        constructor(target: HTMLElement)
        {
            this.load = () =>
            {
                PhotoBlog.Api.AsyncClient.Current.GetAlbums((result) =>
                {
                    var p = result.AlbumMs.map((v) => { return new AlbumVm(v); });
                    this.Albums(p);
                });
            };
            this.load();

            ko.applyBindings(this, target);
        }
    }

    export class PhotoVm
    {
        public url: string = "";
        public urlFull: string = "";
        public showInfo: () => void;
        public hideInfo: () => void;
        public displayInfo: KnockoutObservable<boolean> = ko.observable(false);
        public isActive: KnockoutObservable<boolean> = ko.observable(false);
        public isFullscreen: KnockoutObservable<boolean> = ko.observable(false);
        public description: KnockoutObservable<string> = ko.observable("");
        public music: KnockoutObservable<string> = ko.observable("");
        public musicLink: string = "";
        public pImage: () => void;
        public nImage: () => void;
        public fullScreen: () => void;

        constructor(
            public photo: PhotoBlog.Models.PhotoM,
            public goFullScreen: (data: PhotoVm) => void,
            public prevImage: (photo: PhotoBlog.Models.PhotoM) => void,
            public nextImage: (photo: PhotoBlog.Models.PhotoM) => void
            )
        {

            this.pImage = () =>
            {
                this.prevImage(this.photo);
            };

            this.nImage = () =>
            {
                this.nextImage(this.photo);
            };

            this.fullScreen = () =>
            {
                // this.isFullscreen(!this.isFullscreen());             
            };

            this.description(this.photo.Description != null ? this.photo.Description.trim() : "");
            this.music(this.photo.Music != null ? this.photo.Music.trim() : "");
            var link = "<a href='/day/" + this.photo.Day + "'>Слушать имя</a>";
            this.musicLink = this.photo.Music != null ? link : "";

            this.description.subscribe((newValue) =>
            {
                this.photo.Description = newValue;
            });

            this.music.subscribe((newValue) =>
            {
                this.photo.Music = newValue;
            });

            this.url = '/' + photo.Thumbnail;
            this.urlFull = '/' + photo.Path;
            this.showInfo = () =>
            {
                this.displayInfo(true);
            };

            this.hideInfo = () =>
            {
                this.displayInfo(false);
            };
        }
    }

    export class IndexPageVm
    {
        public Photos: KnockoutObservableArray<PhotoVm> = ko.observableArray<PhotoVm>([]);
        public load: () => void;
        public take: number = 7;
        public skip: number = 0;
        public scrolled: KnockoutObservable<boolean> = ko.observable(true);
        public scrollTo: (id: string) => void;
        public mobileWidth: KnockoutObservable<boolean> = ko.observable(false);
        public enabledEdit: KnockoutObservable<boolean> = ko.observable(false);

        constructor(target: HTMLElement)
        {
            this.scrollTo = (id) =>
            {

            };

            var w = $(window).width();
            if (w < 560) {
                this.mobileWidth(true);
            }

            this.load = () =>
            {
                this.scrolled(false);
                var getPhotosParams = new PhotoBlog.Models.GetPhotosParams();
                getPhotosParams.Skip = this.skip;
                getPhotosParams.Take = this.take;

                PhotoBlog.Api.AsyncClient.Current.GetPhotos(getPhotosParams, (result) =>
                {
                    this.skip = result.Skip;
                    var scrolled = result.Scrolled;
                    if (scrolled) {
                        var p = result.PhotoM.map((v) => { return new PhotoVm(v, () => { }, () => { }, () => { }); });
                        for (var i = 0; i < p.length; i++) {
                            this.Photos.push(p[i]);
                        }
                    }
                    this.scrolled(scrolled);
                });
            };
            this.load();

            ko.applyBindings(this, target);
        }
    }
}

$(document).ready(() =>
{
    var indexPageElem = $("[data-main='true']");
    if (indexPageElem.length > 0) {
        var main = new PhotoBlog.IndexPageVm(indexPageElem[0]);
        //var hash = location.hash.substring(1);
        //main.scrollTo(hash);
    }

    var albumPageElem = $("[data-album='true']");
    if (albumPageElem.length > 0) {
        var album = new PhotoBlog.AlbumPageVm(albumPageElem[0]);
    }

    var albumPhotosElem = $("[data-album-photos='true']");
    if (albumPhotosElem.length > 0) {
        var albumId = Number(albumPhotosElem.attr("data-album-id"));
        var albumPhotos = new PhotoBlog.AlbumPhotosVm(albumPhotosElem[0], albumId);
    }

    var dayPhotoElem = $("[data-day-photo='true']");
    if (dayPhotoElem.length > 0) {
        var numberDay = Number(dayPhotoElem.attr("data-number-day"));
        var onePhoto = new PhotoBlog.OnePhotoVm(albumPhotosElem[0], numberDay);
    };
});